import { defineStore } from 'pinia'
import { ref } from 'vue'

type ThemeType = 'default' | 'red'

const themes = {
  default: {
    '--color-primary': '#2645BA',
    '--tabbar-selected-color': '#2645BA'
  },
  red: {
    '--color-primary': 'red',
    '--tabbar-selected-color': '#red'
  }
}

export const useThemeStore = defineStore(
  'theme',
  () => {
    // 状态定义
    const currentTheme = ref<ThemeType>('default')
    const themeStyle = ref<Record<string, string>>({})

    const setTabBarStyle = () => {
      /* #ifdef MP-WEIXIN */
      /* #endif */

      uni.setTabBarStyle?.({
        selectedColor: themeStyle.value['--color-primary']
      })
    }

    // 公共方法
    const initTheme = () => {
      setTheme(currentTheme.value)
    }

    const setTheme = (theme: ThemeType) => {
      currentTheme.value = theme
      themeStyle.value = themes[theme]
      setTabBarStyle()
    }

    return {
      // 状态
      currentTheme,
      themeStyle,

      // 方法
      initTheme,
      setTheme
    }
  },
  {
    persist: {
      // 显式声明类型
      // key: 'theme', // 设置存储的 key
      // paths: ['mode', 'colors'], // 持久化指定的状态路径
      storage: {
        getItem(key: string) {
          return uni.getStorageSync(key)
        },
        setItem(key: string, value: any) {
          uni.setStorageSync(key, value)
        }
      }
    }
  }
)
